/*
 * @copyright fxsen <br/>
 * @date 2022/4/24 22:55 <br/>
 * @email <a href="mailto:fxsen@foxmail.com">
 * @author fxsen
 */
package com.fxsen.platform.web.controllers;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fxsen.commons.core.annotation.RecordLog;
import com.fxsen.commons.core.annotation.RequiredPermission;
import com.fxsen.commons.core.base.common.entity.JwtUser;
import com.fxsen.commons.core.base.result.ResponseResult;
import com.fxsen.commons.core.constant.Constants;
import com.fxsen.commons.sysmanager.core.entity.Department;
import com.fxsen.commons.sysmanager.core.service.IDepartmentService;
import com.fxsen.commons.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 部门控制器
 * @author fxsen
 * @date 2022/4/24 22:55
 * @email <a href="mailto:fxsen@foxmail.com">
 */
@RestController
@RequestMapping("/department")
@RequiredPermission("department")
@Api(tags = "系统：部门接口")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;
    @ApiOperation(value = "新增")
    @PostMapping("save")
    @RequiredPermission("department:save")
    @RecordLog("新增部门")
    public ResponseResult save(@RequestBody Department department){
        try {
            if (department == null) {
                return ResponseResult.failed("未传请求参数!");
            }
            String name = department.getName();
            if (StringUtils.isBlank(name)){
                return ResponseResult.failed("部门名称不能为空！");
            }
            String code = department.getCode();
            if (StringUtils.isBlank(code)){
                return ResponseResult.failed("部门编码不能为空！");
            }
            if (departmentService.isExist("name",name)){
                return ResponseResult.failed("部门名称”"+name+"“已存在！");
            }
            if (departmentService.isExist("code",code)){
                return ResponseResult.failed("部门编码”"+name+"“已存在！");
            }
            if (StringUtils.isBlank(department.getPid())){
                department.setPid(Constants.PARENT_ID);
            }
            boolean save = departmentService.save(department);
            return save ? ResponseResult.success() : ResponseResult.saveFailed();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "更新")
    @PostMapping("update")
    @RequiredPermission("department:update")
    @RecordLog("更新部门")
    public ResponseResult update(@RequestBody Department department){
        try {
            if (department == null || StringUtils.isBlank(department.getId())) {
                return ResponseResult.failed("未传请求参数!");
            }
            Department oldDept = departmentService.getById(department.getId());
            if (oldDept == null){
                return ResponseResult.failed("数据不存在!");
            }
            String name = department.getName();
            if (StringUtils.isBlank(name)){
                return ResponseResult.failed("部门名称不能为空！");
            }
            String code = department.getCode();
            if (StringUtils.isBlank(code)){
                return ResponseResult.failed("部门编码不能为空！");
            }
            if (!oldDept.getName().equals(name) && departmentService.isExist("name",name)){
                return ResponseResult.failed("部门名称”"+name+"“已存在！");
            }
            if (!oldDept.getCode().equals(code) && departmentService.isExist("code",code)){
                return ResponseResult.failed("部门编码”"+name+"“已存在！");
            }
            if (StringUtils.isBlank(department.getPid())){
                department.setPid(Constants.PARENT_ID);
            }
            BeanUtils.copyProperties(department,oldDept);
            boolean update = departmentService.updateById(oldDept);
            return update ? ResponseResult.success() : ResponseResult.updateFailed();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "删除")
    @GetMapping("delete")
    @RequiredPermission("department:delete")
    @RecordLog("删除部门")
    public ResponseResult delete(@ApiParam("部门主键id") @RequestParam("id") String id){
        try {
            List<Department> departmentList = departmentService.getByPid(id);
            if (CollectionUtils.isNotEmpty(departmentList)){
                return ResponseResult.failed("当前部门有"+departmentList.size()+"个下级，无法删除！");
            }
            boolean remove = departmentService.removeById(id);
            return remove ? ResponseResult.success() : ResponseResult.deleteFailed();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "状态开关")
    @GetMapping("statuSwitch")
    @RecordLog("修改部门状态")
    @RequiredPermission("role:statuSwitch")
    public ResponseResult statuSwitch(@RequestParam("id") String id){
        try {
            Department department = departmentService.getById(id);
            department.setStatus(department.getStatus().equals(Constants.STATUS_NO) ? Constants.STATUS_YES : Constants.STATUS_NO);
            return departmentService.updateById(department) ? ResponseResult.success() : ResponseResult.updateFailed();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "分页列表")
    @GetMapping("page")
    @RequiredPermission("role:page")
    public ResponseResult page(@ApiParam("页码") @RequestParam(value = "page",required = false,defaultValue = "1") int page,
                               @ApiParam("条数") @RequestParam(value = "limit",required = false,defaultValue = "10") int limit,
                               @ApiParam("名称") @RequestParam(value = "name",required = false) String name,
                               @ApiParam("编码") @RequestParam(value = "code",required = false) String code,
                               @ApiParam("状态") @RequestParam(value = "status",required = false) Integer status){
        try {
            LambdaQueryWrapper<Department> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(StringUtils.isNotBlank(name),Department::getName,name);
            queryWrapper.like(StringUtils.isNotBlank(code),Department::getCode,code);
            queryWrapper.eq(null != status,Department::getStatus,status);
            queryWrapper.orderByAsc(Department::getOrderIndex);
            return ResponseResult.success(departmentService.page(new Page<>(page,limit),queryWrapper));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "列表")
    @GetMapping("list")
    @RequiredPermission("role:list")
    public ResponseResult list(@ApiParam("名称") @RequestParam(value = "name",required = false) String name,
                               @ApiParam("编码") @RequestParam(value = "code",required = false) String code,
                               @ApiParam("状态") @RequestParam(value = "status",required = false) Integer status){
        try {
            LambdaQueryWrapper<Department> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(StringUtils.isNotBlank(name),Department::getName,name);
            queryWrapper.like(StringUtils.isNotBlank(code),Department::getCode,code);
            queryWrapper.eq(null != status,Department::getStatus,status);
            queryWrapper.orderByAsc(Department::getOrderIndex);
            return ResponseResult.success(departmentService.list(queryWrapper));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "选择列表")
    @GetMapping("selectList")
    @RequiredPermission("role:selectList")
    public ResponseResult selectList(){
        try {
            LambdaQueryWrapper<Department> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Department::getStatus,Constants.STATUS_YES);
            queryWrapper.orderByAsc(Department::getOrderIndex);
            List<Department> departmentList = departmentService.list(queryWrapper);
            List<Map<String,String>> result = new LinkedList<>();
            departmentList.forEach(department -> {
                Map<String,String> map = new HashMap<>();
                map.put("id",department.getId());
                map.put("pid",department.getPid());
                map.put("name",department.getName());
                map.put("code",department.getCode());
                result.add(map);
            });
            return ResponseResult.success(result);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }

    public static void main(String[] args) {
        JwtUser jwtUser = new JwtUser();
        jwtUser.setUserId("1");
        jwtUser.setname("aaa");
        jwtUser.setAccount("bbbb");
        String token = JwtUtils.buildToken(jwtUser);
        System.out.println(token);
        System.out.println(JSON.toJSONString(JwtUtils.getParamByToken(token)));
    }
}
